<template>
  <div class="scholarship-staff">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>奖学金审核（教师/辅导员/管理员）</span>
              <div class="action-buttons">
                <el-button type="primary" @click="handleCheckScholarship">审核奖学金</el-button>
              </div>
            </div>
          </template>

          <!-- 筛选条 -->
          <el-form :inline="true" class="filter-bar">
            <el-form-item label="奖学金ID">
              <el-input v-model="filters.id" placeholder="输入奖学金ID" clearable style="width: 160px;" />
            </el-form-item>
            <el-form-item label="学号">
              <el-input v-model="filters.studentNum" placeholder="输入学号" clearable style="width: 180px;" />
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="filters.type" placeholder="全部" clearable style="width: 160px;">
                <el-option label="全部" :value="''" />
                <el-option v-for="opt in typeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="filters.status" placeholder="全部" clearable style="width: 160px;">
                <el-option label="全部" :value="''" />
                <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="学年">
              <el-input v-model="filters.applyYear" placeholder="例如 2024-2025" clearable style="width: 180px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchById" :disabled="!filters.id">按ID查询</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>

          <div v-if="!showCheckedList">
            <el-table :data="filteredData" style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="studentNum" label="学号" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="type" label="奖学金类型">
                <template #default="scope">{{ getScholarshipType(scope.row.type) }}</template>
              </el-table-column>
              <el-table-column prop="applyYear" label="申请学年" />
              <el-table-column prop="createTime" label="创建时间" />
              <el-table-column prop="gpaStatus" label="绩点核验">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.gpaStatus === 0 ? 'info' : (scope.row.gpaStatus === 1 ? 'success' : 'danger')">
                    {{ scope.row.gpaStatus === 0 ? '未核验' : (scope.row.gpaStatus === 1 ? '符合' : '不符合') }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="indisciplineStatus" label="违纪核验">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.indisciplineStatus === 0 ? 'info' : (scope.row.indisciplineStatus === 1 ? 'success' : 'danger')">
                    {{ scope.row.indisciplineStatus === 0 ? '未核验' : (scope.row.indisciplineStatus === 1 ? '符合' : '不符合')
                    }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button size="small" @click="viewDetails(scope.row)">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 20px; text-align: right;">
              <el-button type="primary" @click="submitCheck"
                :disabled="selectedScholarships.length === 0">提交审核</el-button>
              <el-button @click="showCheckedList = true">查看已审核列表</el-button>
            </div>
          </div>

          <div v-else>
            <el-table :data="filteredData" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="studentNum" label="学号" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="type" label="奖学金类型">
                <template #default="scope">{{ getScholarshipType(scope.row.type) }}</template>
              </el-table-column>
              <el-table-column prop="applyYear" label="申请学年" />
              <el-table-column prop="createTime" label="创建时间" />
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 20px; text-align: right;">
              <el-button @click="showCheckedList = false">返回待审核列表</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header><span>统计信息</span></template>
          <el-row :gutter="10">
            <el-col :span="12">
              <div class="stat-card">
                <div class="stat-number">{{ totalApplications }}</div>
                <div class="stat-label">申请总数</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-card">
                <div class="stat-number">{{ pendingCount }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-card">
                <div class="stat-number">{{ approvedCount }}</div>
                <div class="stat-label">已批准</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-card">
                <div class="stat-number">{{ rejectedCount }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="680px">
      <div class="detail-content" v-loading="detailLoading">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="奖学金ID">
            {{ String(selectedScholarship?.id ?? '') }}
          </el-descriptions-item>
          <el-descriptions-item label="学号">
            {{ selectedScholarship?.studentNum }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ selectedScholarship?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="奖学金类型">
            {{ getScholarshipType(selectedScholarship?.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请学年">
            {{ selectedScholarship?.applyYear }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ selectedScholarship?.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="绩点核验">
            <el-tag
              :type="selectedScholarship?.gpaStatus === 0 ? 'info' : (selectedScholarship?.gpaStatus === 1 ? 'success' : 'danger')"
              size="small">
              {{ selectedScholarship?.gpaStatus === 0 ? '未核验' : (selectedScholarship?.gpaStatus === 1 ? '符合' : '不符合') }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="违纪核验">
            <el-tag
              :type="selectedScholarship?.indisciplineStatus === 0 ? 'info' : (selectedScholarship?.indisciplineStatus === 1 ? 'success' : 'danger')"
              size="small">
              {{ selectedScholarship?.indisciplineStatus === 0 ? '未核验' : (selectedScholarship?.indisciplineStatus === 1
                ?
                '符合' : '不符合') }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedScholarship?.status)" size="small">
              {{ getStatusText(selectedScholarship?.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="checkDialogVisible" title="审核奖学金" width="500px">
      <el-form :model="checkForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="checkForm.result">
            <el-radio label="1">批准</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input v-model="checkForm.comment" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCheck">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getCheckScholarships, getCheckedScholarships, updateScholarship, rejectScholarship, getScholarshipsByScholarshipId } from '@/api/scholarship'

// 教职端使用的奖学金条目类型（根据后端返回字段进行最小覆盖）
interface ScholarshipItem {
  id: string
  studentNum: string
  name: string
  type: number
  gpaStatus?: number
  indisciplineStatus?: number
  status?: number
  applyYear?: string
  createTime?: string
}

const loading = ref(false)
const scholarshipList = ref<ScholarshipItem[]>([])
const checkedScholarships = ref<ScholarshipItem[]>([])
const selectedScholarships = ref<string[]>([])
const selectedScholarship = ref<ScholarshipItem | null>(null)
const showCheckedList = ref(false)
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const checkDialogVisible = ref(false)
const checkForm = ref({ result: '1', comment: '' })

const totalApplications = computed(() => scholarshipList.value.length)
const pendingCount = computed(() => scholarshipList.value.filter((item: ScholarshipItem) => item.status === 0).length)
const approvedCount = computed(() => scholarshipList.value.filter((item: ScholarshipItem) => item.status === 3).length)
const rejectedCount = computed(() => scholarshipList.value.filter((item: ScholarshipItem) => item.status === 2).length)

const getStatusType = (status?: number) => {
  switch (status) {
    case 0: return 'warning' // 未审核
    case 1: return 'info'    // 审核中
    case 2: return 'danger'  // 审批驳回
    case 3: return 'success' // 审批通过
    default: return 'info'
  }
}
const getStatusText = (status?: number) => {
  switch (status) {
    case 0: return '待审核'
    // case 1: return '审核中'
    case 2: return '审批驳回'
    case 3: return '审批通过'
    default: return '未知状态'
  }
}
const getScholarshipType = (type?: number) => {
  switch (type) {
    case 1: return '国家奖学金'
    case 2: return '国家励志奖学金'
    case 3: return '校级奖学金'
    case 4: return '专业奖学金'
    default: return '未知类型'
  }
}

// 筛选相关
const filters = ref<{ id: string; studentNum: string; type: string | number; status: string | number; applyYear: string }>({
  id: '',
  studentNum: '',
  type: '',
  status: '',
  applyYear: ''
})
const typeOptions = computed(() => [
  { label: '国家奖学金', value: 1 },
  { label: '国家励志奖学金', value: 2 },
  { label: '校级奖学金', value: 3 },
  { label: '专业奖学金', value: 4 }
])
const statusOptions = computed(() => [
  { label: '待审核', value: 0 },
  { label: '审核中', value: 1 },
  { label: '审批驳回', value: 2 },
  { label: '审批通过', value: 3 }
])
// 如果执行了按 ID 查询，优先显示 ID 查询结果
const idSearchResult = ref<ScholarshipItem[] | null>(null)
const displayedList = computed(() => idSearchResult.value ?? (showCheckedList.value ? checkedScholarships.value : scholarshipList.value))
const filteredData = computed(() => {
  const sn = (filters.value.studentNum || '').trim()
  const type = filters.value.type !== '' ? Number(filters.value.type) : null
  const status = filters.value.status !== '' ? Number(filters.value.status) : null
  const year = (filters.value.applyYear || '').trim()
  return displayedList.value.filter(item => {
    const matchSn = sn ? String(item.studentNum).includes(sn) : true
    const matchType = type != null ? item.type === type : true
    const matchStatus = status != null ? item.status === status : true
    const matchYear = year ? String(item.applyYear || '').includes(year) : true
    return matchSn && matchType && matchStatus && matchYear
  })
})
const resetFilters = () => {
  filters.value = { id: '', studentNum: '', type: '', status: '', applyYear: '' }
  idSearchResult.value = null
}

// 按奖学金ID查询（跨列表精准命中，不受当前列表筛选影响）
const searchById = async () => {
  const rawId = (filters.value.id || '').trim()
  if (!rawId) {
    ElMessage.warning('请输入奖学金ID')
    return
  }
  try {
    const resp = await getScholarshipsByScholarshipId(rawId)
    if (String(resp.code) === '200' && resp.data) {
      const data = Array.isArray(resp.data) ? (resp.data[0] || null) : resp.data
      if (!data) {
        ElMessage.info('未找到对应奖学金记录')
        idSearchResult.value = []
        return
      }
      // 规范化字段以适配表格展示
      const normalized: ScholarshipItem = {
        id: String((data as any).id),
        studentNum: String((data as any).studentNum || ''),
        name: String((data as any).name || ''),
        type: Number((data as any).type || 0),
        applyYear: String((data as any).applyYear || ''),
        createTime: String((data as any).createTime || ''),
        gpaStatus: Number((data as any).gpaStatus ?? 0),
        indisciplineStatus: Number((data as any).indisciplineStatus ?? 0),
        status: Number((data as any).status ?? 0)
      }
      idSearchResult.value = [normalized]
      // 切换到待审核视图以保持操作按钮一致（不强制，但更统一）
      showCheckedList.value = false
    } else {
      ElMessage.error((resp as any)?.msg || '查询失败')
      idSearchResult.value = []
    }
  } catch (e) {
    ElMessage.error('查询失败，请稍后重试')
    idSearchResult.value = []
  }
}

// 加载待审核/审核中的奖学金列表
const loadScholarshipList = async () => {
  try {
    loading.value = true
    // 加载待审核/审核中的列表
    const response = await getCheckScholarships()
    console.log('查询到的原始数据:', response.data)

    if (response.code === '200') {
      const arr = Array.isArray(response.data) ? response.data : []
      scholarshipList.value = arr.map((it: any) => ({
        ...it,
        id: String(it?.id)
      }))
    } else {
      ElMessage.error(response.msg || '获取奖学金列表失败')
    }
  } catch (error) {
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 加载已审核的奖学金列表
const loadCheckedScholarships = async () => {
  try {
    loading.value = true
    const response = await getCheckedScholarships()
    if (response.code === '200') {
      const arr = Array.isArray(response.data) ? response.data : []
      checkedScholarships.value = arr.map((it: any) => ({
        ...it,
        id: String(it?.id)
      }))
    } else {
      ElMessage.error(response.msg || '获取已审核列表失败')
    }
  } catch (error) {
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection: ScholarshipItem[]) => {
  selectedScholarships.value = selection.map(item => String(item.id))
}
const viewDetails = async (row: ScholarshipItem) => {
  try {
    detailLoading.value = true
    const resp = await getScholarshipsByScholarshipId(String(row.id))
    if (String(resp.code) === '200' && resp.data) {
      const data = resp.data as any
      // 合并行基础信息与接口详情，保证字段完整
      selectedScholarship.value = { ...row, ...data, id: String((data?.id) ?? row.id) }
    } else {
      ElMessage.error((resp as any)?.msg || '获取详情失败')
      selectedScholarship.value = row
    }
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取详情失败，请稍后重试')
    selectedScholarship.value = row
    detailDialogVisible.value = true
  } finally {
    detailLoading.value = false
  }
}
const handleCheckScholarship = () => {
  if (selectedScholarships.value.length === 0) {
    ElMessage.warning('请选择要审核的奖学金申请')
    return
  }
  checkDialogVisible.value = true
}
const submitCheck = () => {
  checkDialogVisible.value = true
}

const confirmCheck = async () => {
  try {
    loading.value = true
    checkDialogVisible.value = false

    const ids = selectedScholarships.value.map(id => String(id))
    let resp
    if (checkForm.value.result === '1') {
      // 同意：调用通过接口
      resp = await updateScholarship(ids)
    } else {
      // 拒绝：调用驳回接口
      resp = await rejectScholarship(ids)
    }
    console.log('审批提交响应:', resp)
    if (resp.code === '200') {
      ElMessage.success(checkForm.value.result === '1' ? '审批提交成功' : '已拒绝所选申请')
    } else {
      ElMessage.error(resp.msg || '提交失败')
    }

    await loadScholarshipList()
    selectedScholarships.value = []
  } catch (error) {
    ElMessage.error('审核失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadScholarshipList()
})

// 切换查看已审核列表/待审核列表时，自动加载对应数据
watch(showCheckedList, async (val) => {
  if (val) {
    await loadCheckedScholarships()
  } else {
    await loadScholarshipList()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.stat-card {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  margin-bottom: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.detail-content {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.detail-label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.detail-value {
  color: #303133;
  flex: 1;
}
</style>